package com.voice.core.connection.frame;

import com.voice.core.connection.Connection;
import com.voice.core.exception.ClientException;
import com.voice.core.utils.BytesUtil;

import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class StreamFrame extends AbstractFrame{

    private InputStream inputStream;

    public StreamFrame(){}

    public StreamFrame(int streamId, InputStream inputStream){
        this.streamId=streamId;
        this.type=FrameType.stream.getType();
        ByteBuffer buffer=ByteBuffer.allocate(headerLength);
        buffer.put(BytesUtil.intToBytes(0,3));
        buffer.put(type);
        buffer.put((byte) 0);
        buffer.putInt(streamId);
        payload=buffer.array();
        this.inputStream=inputStream;
    }

    @Override
    public int readHeader(byte[] bytes) {
        return super.readHeader(bytes,512);
    }

    @Override
    public byte[] getData() {
        byte[] bytes=Arrays.copyOfRange(payload, headerLength,position);
        position=headerLength;
        return bytes;
    }

    @Override
    public int write(ByteBuffer buffer) {
        try {
            if(position<headerLength) return super.write(buffer);
            int size=inputStream.read(buffer.array(),buffer.position(),buffer.remaining());
            buffer.position(buffer.position()+size);
            return size;
        } catch (IOException e) {
            throw new ClientException(e);
        }
    }

    @Override
    public boolean readFinish() {
        return true;
    }

    @Override
    public boolean writeFinish() {
        return false;
    }

    @Override
    public void onFinish(Connection connection) {
        connection.onStreamRead(streamId,getData());
    }
}
